package models

import (
	"arti-manage/appconfig"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"sync"
)

var DB *gorm.DB
var err error

func Init() {
	var once sync.Once
	mysqlCofig := appconfig.AppCof.Mysql
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		mysqlCofig.User,
		mysqlCofig.Password,
		mysqlCofig.Host,
		mysqlCofig.Port,
		mysqlCofig.Database)
	once.Do(func() {
		DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	})
	if err != nil {
		panic(err)
	}
	fmt.Println("mysql 连接成功")
	err = DB.AutoMigrate(&Article{})
	if err != nil {
		panic(err)
	}
	fmt.Println("数据表迁移成功")

}
